package cn.xiaolang.function.data_structure;

import java.util.HashMap;
import java.util.Map;

/**
 * 14.最长公共前缀
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串""。
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 * 示例 2：
 * <p>
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *
 * @author Dean
 * @date 2022/6/1
 */
public class No9longestCommonPrefix {

    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(longestCommonPrefix(new String[]{"cir", "car"}));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int numbers = strs.length;
        String firstStr = strs[0];
        // 纵向比较：已第一个字符为基准，逐位字符比较是否相同
        for (int i = 0; i < firstStr.length(); i++) {
            char c = firstStr.charAt(i);
            for (int j = 1; j < numbers; j++) {
                // 其余字符串长度大于第一个字符串。或者中间某个字符已经不相同
                if (strs[j].length() == i || strs[j].charAt(i) != c) {
                    return firstStr.substring(0, i);
                }
            }
        }
        return firstStr;
    }

    public static String longestCommonPrefixMine(String[] strs) {
        int numbers = strs.length;
        StringBuilder commonPrefix = new StringBuilder();
        int shortest = strs[0].length();
        for (int i = 1; i < numbers; i++) {
            if (shortest > strs[i].length()) {
                shortest = strs[i].length();
            }
        }
        Map<String, Integer> stat = new HashMap<>();
        int sameIndex = 0;
        for (int i = 0; i < numbers; i++) {
            char[] chars = strs[i].toCharArray();
            for (int j = 0; j < shortest; j++) {
                String key = chars[j] + "_" + j;
                if (stat.containsKey(key)) {
                    stat.put(key, stat.get(key) + 1);
                } else {
                    stat.put(key, 1);
                }
                if (stat.get(key) == numbers && j == sameIndex) {
                    commonPrefix.append(chars[j]);
                    sameIndex = j + 1;
                }
            }
        }
        return commonPrefix.toString();
    }

}
